package com.mystnihon.freeremote.loader.torrent;

import java.io.IOException;

import android.util.Log;
import ca.benow.transmission.TransmissionClient;

import com.mystnihon.freeremote.config.Config;
import com.octo.android.robospice.request.SpiceRequest;

public class StartStopTorrentRequest extends SpiceRequest<Void> {
    private static final String TAG = StartStopTorrentRequest.class.getSimpleName();
    boolean mStart = false;
    Object[] mIds;
    TransmissionClient mclient;

    public StartStopTorrentRequest(TransmissionClient client, boolean startTorrent, Object... ids) {
        super(Void.class);
        mStart = startTorrent;
        mIds = ids;
        mclient = client;
    }

    @Override
    public Void loadDataFromNetwork() throws Exception {
        if (mIds.length > 0) {
            if (mStart) {
                try {
                    if (Config.DEBUG_MODE_ENABLED) {
                        Log.d(TAG, "start torrent");
                    }
                    mclient.startTorrents(mIds);
                } catch (IOException e) {
                    if (Config.WARNING_MODE_ENABLED) {
                        Log.w(TAG, "Erreur while trying to start torrents : " + mIds, e);
                        throw e;
                    }
                }
            } else {
                try {
                    if (Config.DEBUG_MODE_ENABLED) {
                        Log.d(TAG, "stop torrent");
                    }
                    mclient.stopTorrents(mIds);
                } catch (IOException e) {
                    if (Config.WARNING_MODE_ENABLED) {
                        Log.w(TAG, "Erreur while trying to stop torrents : " + mIds, e);
                    }
                    throw e;
                }
            }
        } else {
            if (mStart) {
                try {
                    if (Config.DEBUG_MODE_ENABLED) {
                        Log.d(TAG, "start torrents");
                    }
                    mclient.startAllTorrents();
                } catch (IOException e) {
                    if (Config.WARNING_MODE_ENABLED) {
                        Log.w(TAG, "Erreur while trying to stop all torrents", e);
                        throw e;
                    }
                }
            } else {
                try {
                    if (Config.DEBUG_MODE_ENABLED) {
                        Log.d(TAG, "stop torrents");
                    }
                    mclient.stopAllTorrents();
                } catch (IOException e) {
                    if (Config.WARNING_MODE_ENABLED) {
                        Log.w(TAG, "Erreur while trying to stop all torrents", e);
                    }
                    throw e;
                }
            }
        }
        return null;
    }
}
